/*
 * MemCached.h
 *
 *  Created on: 2013. 10. 8.
 *      Author: the2
 */

#ifndef MEMCACHED_H_
#define MEMCACHED_H_

#include "Pattern.h"
#include <libmemcached/memcached.h>
#include "User.h"

#define Memcache FriendsServer::MemCached::GetInstance()

namespace FriendsServer {

const char * const __USER__			= "user_";
const char * const __SCORE__		= "score_";
const char * const __LOCATION__		= "location_";
const char * const __MEDAL__		= "medal_";
const char * const __RANK__			= "rank_";

class MemCachedData
{
public:

	struct Score
	{
		uint32_t	curweek;
		uint32_t	lastweek;
		time_t		reg_date;
		time_t		last_reg_date;

		Score() : curweek(0), lastweek(0), reg_date(0), last_reg_date(0) {}
	};

	struct Medal
	{
		int	gold;
		int silver;
		int bronze;

		Medal() : gold(0), silver(0), bronze(0) {}

		void Clear()
		{
			gold	= 0;
			silver	= 0;
			bronze	= 0;
		}
	};

	struct ServerLocation
	{
		uint32_t server_id;
		uint32_t channel_id;

		ServerLocation() : server_id(0), channel_id(0) {}
	};

public:
	MemCachedData();
	virtual ~MemCachedData();
};

class MemCached : public pattern::Singleton<MemCached>
{
	friend class pattern::Singleton<MemCached>;

public:
	bool Init(const char *address);
	bool Release();

	memcached_return_t Set( const char *key, const char *value, const size_t size, time_t expiration );
	char* Get( const char *key, size_t *valueLen, uint32_t *flags, memcached_return_t *error );

	memcached_return_t MGet( const char* const *keys, const size_t *key_length, size_t number_of_keys );
	char* Fetch( char *return_key, size_t *return_key_length, size_t *value_length, uint32_t *flags, memcached_return_t *error );

	memcached_return_t Delete( const char *key, size_t key_length, time_t expiration );
	const char* GetErrorString( memcached_return_t rc );

	memcached_return_t FlushAll();

	int 	SetMyInfo(std::shared_ptr<User> & clsuser);
	int 	GetInfoSocialMine(std::shared_ptr<User> & clsuser);
	int 	GetInfoSocialOther(std::shared_ptr<User> clsuser, const uint32_t friendSeq, User::UserInfo & userinfo);

	int		GetScore(const uint32_t userSeq, MemCachedData::Score & score);
	bool	GetLocation(const uint32_t userSeq, MemCachedData::ServerLocation & serverLocation);
	int		GetMedal(const uint32_t userSeq, MemCachedData::Medal & medal);

private:
	MemCached():pMemc(0), pServer(0) {};
	virtual ~MemCached() {};
	memcached_st		*pMemc;
	memcached_server_st	*pServer;
};

} /* namespace FriendsServer */

#endif /* MEMCACHED_H_ */
